<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="120px" size="mini">
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="合同名称" require prop="name">
            <el-input v-model="formItem.name" placeholder="请输入合同名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="合同号" require prop="code">
            <el-input v-model="formItem.code" placeholder="请输入合同号" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="签订时间" require prop="signingDate">
            <el-date-picker
              v-model="formItem.signingDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="请选择签订时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供应商" require prop="manufacturerName">
            <el-input v-model="formItem.manufacturerName" placeholder="请输入供货方联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系人" require prop="manufacturerContact">
            <el-input v-model="formItem.manufacturerContact" placeholder="请输入供货方联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系人电话" require prop="manufacturerTelephone">
            <el-input v-model="formItem.manufacturerTelephone" placeholder="请输入供货方联人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="合同描述" require prop="description">
            <el-input v-model="formItem.description" placeholder="请输入合同描述" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件">
            <el-upload
              class="upload-demo"
              :headers="headers"
              :action="importUrl"
              :file-list="formItem.attachment"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-remove="handleRemove"
              :show-file-list="true"
            >
              <el-button size="small" type="primary" icon="el-icon-upload2">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { clone } from '@neu/biz-core/utils/utils'
import { deepClone } from '@neu/biz-core/utils'
import { getToken } from '@neu/biz-core/utils/auth'
import {
  create,
  update,
  detail,
  uploadFileUrl
} from '@neu/dcam-ui/api/contract'

// 定义一个表单原始项
const formItem = {
  name: '',
  code: '',
  manufacturerName: '',
  manufacturerContact: '',
  manufacturerTelephone: '',
  signingDate: null,
  description: '',
  attachment: []
}
export default {
  name: 'ContractEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: clone(formItem),
      // 合同详细编辑
      obj: null,
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '合同名称不能为空', trigger: 'blur' },
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '合同号不能为空', trigger: 'blur' },
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        manufacturerName: [
          { required: true, message: '供应商不能为空', trigger: 'blur' },
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        manufacturerContact: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        manufacturerTelephone: [
          { required: true, message: '联系人电话不能为空', trigger: 'blur' }
        ],
        signingDate: [{ required: true, message: '签订时间不能为空', trigger: 'blur' }]
      },
      modal: true,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      importUrl: uploadFileUrl
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          const data = response.data
          if (data.attachment) {
            const fileJoins = data.attachment.split('||')
            data.attachment = fileJoins.map(it => {
              const fsInfo = it.split('@@')
              return {
                fsId: fsInfo[0],
                name: fsInfo[1]
              }
            })
          } else {
            data.attachment = []
          }

          this.formItem = {
            ...data
          }
          // 标记初始化数据
          // this.formItem.items.forEach(k => {
          //   k['init'] = true
          // })
        })
      } else {
        this.formItem = clone(formItem)
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            const deepCloneForm = deepClone(this.formItem)
            // 将附件转为字符串存储
            if (deepCloneForm.attachment.length > 0) {
              deepCloneForm.attachment = deepCloneForm.attachment.map(it => it.fsId + '@@' + it.name).join('||')
            } else {
              deepCloneForm.attachment = ''
            }

            if (updated) {
              resolve(update(this.id, deepCloneForm))
            } else {
              resolve(create(deepCloneForm))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.formItem = clone(formItem)
    },
    /** 文件上传成功 */
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.attachment.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachment.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    /** 文件上传失败 */
    handleError(err, file, fileList) {
      console.error(err)
    },
    /** 文件移除 */
    handleRemove(file, fileList) {
      this.formItem.attachment.splice(this.formItem.attachment.indexOf(file), 1)
    }
  }
}
</script>
